package com.qianxx.viewlibrary.effects.waves;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

/**
 * 点击具有水波纹效果的RelativLayout
 */
public class WavesRelativeLayout extends RelativeLayout implements Animator.AnimatorListener {
    private Paint paint = new Paint();
    //当前水波扩散进度
    private float progress;
    //动画持续时间
    private long duration = 1000;
    //水波扩散中心
    private float x, y;
    //水波颜色
    private int wavesColor = Color.parseColor("#d9d9d9");

    public float getProgress() {
        return progress;
    }

    public void setProgress(float progress) {
        this.progress = progress;
        invalidate();
    }

    public WavesRelativeLayout(Context context) {
        this(context, null);
    }

    public WavesRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WavesRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint.setColor(wavesColor);
    }

    @Override
    public void onDrawForeground(Canvas canvas) {
        super.onDrawForeground(canvas);
        paint.setAlpha((int) (100 - progress));
        canvas.drawCircle(x, y, getWidth() * progress / 100, paint);
    }

    /**
     * 开始执行动画
     */
    private void startAnimation() {
        setLayerType(LAYER_TYPE_HARDWARE, null);
        ObjectAnimator an = ObjectAnimator.ofFloat(this, "progress", 0, 100);
        an.setDuration(duration);
        an.start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                y = event.getY();
                startAnimation();
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:

                break;
            case MotionEvent.ACTION_CANCEL:

                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onAnimationStart(Animator animator) {

    }

    @Override
    public void onAnimationEnd(Animator animator) {
        setLayerType(LAYER_TYPE_NONE, null);
    }

    @Override
    public void onAnimationCancel(Animator animator) {

    }

    @Override
    public void onAnimationRepeat(Animator animator) {

    }
}
